<?php

    Yii::import('zii.widgets.CMenu');
    
    class TopMenuAbstract extends CMenu{

          
        public function run()
        {
             $currentLang = Yii::app()->language;
             $query  = "SELECT   MENU_CODE,"
                    . "         FN_QTC_MULTI_NAME(MENU_NAME, MENU_ENG_NAME, :LANG_CODE) AS MENU_NAME, "
                    . "         PARENT_MENU_CODE, "
                    . "         SORT_ORDER, "
                    . "         USE_YN "
                    . "         FROM TB_QTC_MENU"
                    . "         WHERE USE_YN = 'Y' "
                    . "         ORDER BY SORT_ORDER ";
                    
                $command = Yii::app()->db->createCommand($query);
                $results = $command->queryAll(true, array(':LANG_CODE' => $currentLang));
                
                $this->renderCustomMenu($results);
        }
        // render menu 
        private function renderCustomMenu($results) {

            $data  = $this->buildTreeArray($results);
            $html  = '<ul>';
            $html .= $this->buildTreeHtml($data);
            $html .= '</ul>';
            echo $html;
          
       }
       // get tree array
       private function buildTreeArray(array $elements, $parentId = null) {
            $branch = array();
        
            foreach ($elements as $element) {
                if ($element['PARENT_MENU_CODE'] == $parentId) {
                    $children = self::buildTreeArray($elements, $element['MENU_CODE']);
                    if($children) {
                        $element['CHILDREN'] = $children;
                    }
                    $branch[] = $element;
                }
            }
        
            return $branch;
       }
        // get tree html
        private function buildTreeHtml(array $elements) {
            $html = "";

            foreach ($elements as $element) {
                if(isset($element['CHILDREN']) && sizeof($element['CHILDREN']) > 0){
                    $html .= '<li><a>'.$element['MENU_NAME'].'</a>';
                    $html .= '<ul>';
                    $html .= self::buildTreeHtml($element['CHILDREN']);
                    $html .= '</ul>';
                    $html .= '</li>';
                }else{
                    $html .= '<li><a >'.$element['MENU_NAME'].'</a></li>';
                }
            }

            return $html;
        }

     
    }
?>